﻿using System;
using System.Collections.Generic;
using System.Web;

using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.IO.Compression;
namespace HuoTu.Common
{
    /// <summary>
    /// 目前采用DeflateStream压缩
    /// </summary>
    public class SysZip
    {
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static byte[] Compress(object obj)
        {
            if (obj == null) return null;
            MemoryStream mStream = null;
            MemoryStream oStream = null;
            DeflateStream zipStream = null;
            try
            {
                BinaryFormatter bFormatter = new BinaryFormatter();
                mStream = new MemoryStream();
                bFormatter.Serialize(mStream, obj);
                byte[] bytes = mStream.ToArray();
                oStream = new MemoryStream();
                zipStream = new DeflateStream(oStream, CompressionMode.Compress);
                zipStream.Write(bytes, 0, bytes.Length);
                zipStream.Flush();
                zipStream.Close();
                return oStream.ToArray();
            }
            catch
            {
                return null;
            }
            finally
            {
                if (zipStream != null) zipStream.Close();
                if (oStream != null) oStream.Close();
                if (mStream != null) mStream.Close();
            }
        }
        /// <summary>
        /// 解压缩
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static object DeCompress(byte[] bytes)
        {
            if (bytes == null) return null;
            MemoryStream mStream = null;
            DeflateStream unZipStream = null;
            try
            {
                mStream = new MemoryStream(bytes);
                mStream.Seek(0, SeekOrigin.Begin);
                unZipStream = new DeflateStream(mStream, CompressionMode.Decompress, true);
                object dsResult = null;
                BinaryFormatter bFormatter = new BinaryFormatter();
                dsResult = (object)bFormatter.Deserialize(unZipStream);
                return dsResult;
            }
            catch
            {
                return null;
            }
            finally
            {
                if (unZipStream != null) unZipStream.Close();
                if (mStream != null) mStream.Close();
            }
        }
    }
}